package config

import (
	"encoding/json"

	"infosec.com.cn/crypto-http/config/ntv"
)

type Response struct {
	needMarshal bool
	Status      *Status    `json:"Status"`
	Data        []*ntv.NTV `json:"Data,omitempty"`
}
type Status struct {
	Code    string `json:"Code"`
	Message string `json:"Msg"`
}

func NewRespondWithoutMarshal() *Response {
	return &Response{
		needMarshal: false,
		Data:        make([]*ntv.NTV, 0),
	}
}

func NewRespond() *Response {
	return &Response{
		needMarshal: true,
		Status:      &Status{Code: "0", Message: "success"},
		Data:        make([]*ntv.NTV, 0),
	}
}

// append 拼接多个 ntv.NTV, 返回当前位置
func (resp *Response) Append(data *ntv.NTV) int {
	resp.Data = append(resp.Data, data)
	return len(resp.Data) - 1
}

func (resp *Response) Marshal() ([]byte, error) {
	if resp.needMarshal {
		for _, data := range resp.Data {
			data.Marshal()
		}
	}
	return json.Marshal(resp)
}

func (resp *Response) MarshalIndent(prefix, indent string) ([]byte, error) {
	if resp.needMarshal {
		for _, data := range resp.Data {
			data.Marshal()
		}
	}
	return json.MarshalIndent(resp, prefix, indent)
}
